//
//   ______    ______    ______
//  /\  __ \  /\  ___\  /\  ___\
//  \ \  __<  \ \  __\_ \ \  __\_
//   \ \_____\ \ \_____\ \ \_____\
//    \/_____/  \/_____/  \/_____/
//
//  Powered by BeeFramework
//
//
//  GoodM.m
//  Pizza
//
//  Created by sendInfo on 2015-03-31.
//  Copyright (c) 2015年 sendInfo. All rights reserved.
//

#import "GoodM.h"

#pragma mark -
@interface GoodM()
{
    
    NSUInteger _page;
    
}
@end

@implementation GoodM

- (void)load
{
    [self loadCache];
}

- (void)unload
{
    [self saveCache];
}

- (NSString *)cacheKey
{
    // You should set an identified key if this model is shared.
    return NSStringFromClass([self class]);
}

- (void)loadCache
{
    NSData * data = bee.system.fileCache[self.cacheKey];
    if ( data )
    {
        [self.goodsArr removeAllObjects];
        [self.goodsArr addObjectsFromArray:[NSObject objectsFromAny:data]];
    }
}

- (void)saveCache
{
    bee.system.fileCache[self.cacheKey] = [self.goodsArr objectToData];
}

- (void)clearCache
{
    bee.system.fileCache[self.cacheKey] = nil;
    
    [self.goodsArr removeAllObjects];
    
    self.loaded = NO;
}

#pragma mark -

- (void)firstPage
{
    
    _page = 1;
    [self gotoPage:1];
    
}
- (void)nextPage
{
    
    _page++;
    
    [self gotoPage:_page];
    
}
- (void)gotoPage:(NSUInteger)page
{
    self.CANCEL_MSG(HttpAPI.products);
    
    NSDictionary *dic = @{@"shopId":self.shopId,
                          @"pageSize":@"1000",
                          @"pageNumber":@(_page),
                          @"token":[SendIFAPPDefault shareAppDefault].userToken,
                          @"categoryId":@"",
                          @"keywords":self.keywords};
    
    self.MSG(HttpAPI.products).INPUT(@"body",dic);
}

ON_MESSAGE3(HttpAPI, products, msg)
{
    
    if (msg.sending) {
        
        
        [self sendUISignal:self.RELOADING];
        
    }else {
        
        
        if (msg.succeed) {
            
            Status *sta = msg.GET_OUTPUT(@"status");
            if ([sta.code intValue] != 10000) {
                
                msg.failed = YES;
                
            }
            
            if (_page == 1) {
                
                [self.goodsArr removeAllObjects];
                self.goodsArr = msg.GET_OUTPUT(@"goods");
                
            }else{
                
                [self.goodsArr addObjectsFromArray:msg.GET_OUTPUT(@"goods")];
//                int all = [msg.GET_OUTPUT(@"totallNum") intValue];
//                self.more = self.goodsArr.count >= all? NO : YES;
                //[self saveCache];
                
            }
            
            
        }
        
        
        [self sendUISignal:self.RELOADED];
        
        
    }
}

@end